#include "comm.hpp"

#include <iostream>
#include <cstring>
#include <cerrno>
#include <string>
#include <unistd.h>
using namespace std;

int main()
{
    //创建命名管道
    int CreateChannelCode = mkfifo(FIFO_FILE, MODE);
    if(CreateChannelCode == -1)
    {
        cerr << "Error creating FIFO: " << strerror(errno) << endl;
        return CREATCHANNELERROR;
    }
    //打开管道的读端口（读取子进程写入的数据）
    int fd = open(FIFO_FILE, O_RDONLY);
    if(fd == -1)
    {
        cerr << "Error opening FIFO: " << strerror(errno) << endl;
        return OPENCHANNELERROR;
    }
    cout<<"通信已经建立，等待消息..."<<endl;
    //开始通信
    while(true)
    {
        char buffer[SIZE];
        buffer[0] = 0; //告诉阅读者该数组充当字符串
        ssize_t bytesRead = read(fd, buffer, SIZE - 1);
        if (bytesRead > 0)
        {
            buffer[bytesRead] = 0; //确保字符串以\0结尾
            cout << "Received: " << buffer << endl;
        }
        else if(bytesRead == 0)
        {
            cout << "End of file reached, exiting." << endl;
            break; //管道关闭，退出循环
        }
        else
        {
            cerr << "Error reading from FIFO: " << strerror(errno) << endl;
            break; //发生错误，退出循环
        }
    }
    //关闭管道
    close(fd);
    int CloseChannelCode = unlink(FIFO_FILE);
    if(CloseChannelCode == -1)
    {
        cerr << "Error closing FIFO: " << strerror(errno) << endl;
        return CLOSECHANNELERROR;
    }
    return 0;
}